﻿using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;


namespace Nasa8x.Web.UI
{
    [ToolboxData("<{0}:HtmlEditor runat=\"server\"></{0}:HtmlEditor>")]
    public sealed class HtmlEditor : TextBox
    {

        private string _plugins = "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,inlinepopups,filemanager";
        private const string ControlName = "Editor";
        private string _sScriptPath = "/HtmlEditor/";

        private string[] _sAdvancedToolBarButtons = new[]
                                                {
                                                    "paste,pastetext,pasteword,|,undo,redo,cleanup,|,tablecontrols,|,hr,removeformat,visualaid,|,insertlayer,moveforward,movebackward,absolute", 
                                                    "search,replace,|,bullist,numlist,outdent,indent,blockquote,|,sub,sup,|,ltr,rtl,|,cite,abbr,acronym,del,ins,attribs,|,charmap,emotions,iespell,advhr,|,image,media,|,code,preview,fullscreen", 
                                                    "styleprops,forecolor,backcolor,fontselect,fontsizeselect,formatselect,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,link,unlink,anchor",
                                                    ""
                                                };

        private readonly string[] _sMediumToolBarButtons = new[] { 
                                                        "pastetext,|,search,replace,|,bullist,numlist,outdent,indent,blockquote,|,sub,sup,|,ltr,rtl,|,cite,abbr,acronym,del,ins,attribs,|,charmap,emotions,iespell,advhr,|,image,media,|,code,preview,fullscreen", 
                                                        "styleprops,forecolor,backcolor,fontselect,fontsizeselect,formatselect,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,link,unlink,anchor",
                                                        "",
                                                        ""
                                                        };


        private readonly NameValueCollection _SkinNameValues;


        #region Contactor

        public HtmlEditor()
        {

            _SkinNameValues = new NameValueCollection
                                  {
                                      {"default", "skin:default"},
                                      {"office2007blue", "skin : \"o2k7\",skin_variant :\"blue\""},
                                      {"office2007silver", "skin : \"o2k7\",skin_variant :\"silver\""},
                                      {"office2007black", "skin : \"o2k7\",skin_variant :\"black\""}
                                  };
        }

        #endregion

        #region Enum

        public enum EditorToolBarLocation
        {
            Top,
            Bottom
        }

        public enum EditorToolBarAlign
        {
            Left,
            Right
        }

        public enum EditorStatusBarLocation
        {
            Top,
            Bottom,
            None
        }

        public enum EditorThemeMode
        {
            Simple,
            Advanced
        }


        public enum EditorSkin
        {
            Office2007Blue,
            Office2007Silver,
            Office2007Black
        }



        #endregion

        #region Properties

      

        public bool FileManagerEnable
        {

            get
            {
                object _o = ViewState["FileManagerEnable"];
                if (_o != null)
                    return (bool)_o;
                return true;

            }
            set { ViewState["FileManagerEnable"] = value; }
        }



        public bool IsAjaxEnable
        {

            get
            {

                object _o = ViewState["IsAjaxEnable"];
                if (_o != null)
                    return (bool)_o;
                return true;

            }
            set { ViewState["IsAjaxEnable"] = value; }
        }

        public string ScriptPath
        {
            get
            {

                if (!_sScriptPath.EndsWith("/")) _sScriptPath += "/";
                return _sScriptPath;

            }
            set
            {

                _sScriptPath = value;
            }

        }

        public string Plugins
        {
            get
            {
                return _plugins;
            }
            set
            {
                _plugins = value;
            }
        }

        public string[] ToolBarButtons
        {
            get
            {
                return _sAdvancedToolBarButtons;
            }
            set { _sAdvancedToolBarButtons = value; }
        }


        public EditorToolBarLocation ToolBarLocation
        {
            get
            {
                object o = ViewState["ToolBarLocation"];
                return o == null ? EditorToolBarLocation.Top : (EditorToolBarLocation)o;
            }
            set
            {
                ViewState["ToolBarLocation"] = value;
            }

        }

        public EditorToolBarAlign ToolBarAlign
        {
            get
            {
                object o = ViewState["ToolBarAlign"];
                return o == null ? EditorToolBarAlign.Left : (EditorToolBarAlign)o;
            }
            set
            {
                ViewState["ToolBarAlign"] = value;
            }

        }

        public enum EditorToolBarMode
        {
            Simple,
            Medium,
            Advanced
        }

        public EditorToolBarMode ToolBarMode
        {
            get
            {
                object o = ViewState["ToolBarMode"];
                return o == null ? EditorToolBarMode.Advanced : (EditorToolBarMode)o;
            }
            set
            {
                ViewState["ToolBarMode"] = value;
            }

        }


        public EditorThemeMode ThemeMode
        {
            get
            {
                object o = ViewState["ThemeMode"];
                return o == null ? EditorThemeMode.Advanced : (EditorThemeMode)o;
            }
            set
            {
                ViewState["ThemeMode"] = value;
            }

        }


        public EditorStatusBarLocation StatusBarLocation
        {
            get
            {
                object o = ViewState["StatusBarLocation"];
                return o == null ? EditorStatusBarLocation.Bottom : (EditorStatusBarLocation)o;
            }
            set
            {
                ViewState["StatusBarLocation"] = value;
            }

        }

      
        public bool Resizing
        {

            get
            {
                object _o = ViewState["Resizing"];
                if (_o != null)
                    return (bool)_o;
                return true;

            }
            set { ViewState["Resizing"] = value; }
        }


        public EditorSkin Skin
        {

            get
            {
                object o = ViewState["Skin"];
                return o == null ? EditorSkin.Office2007Blue : (EditorSkin)o;
            }
            set
            {
                ViewState["Skin"] = value;
            }

        }


        public bool ConvertUrls
        {

            get
            {
                object _o = ViewState["ConvertUrls"];
                if (_o != null)
                    return (bool)_o;
                return false;

            }
            set { ViewState["ConvertUrls"] = value; }
        }


        private string ClientSkinString
        {
            get
            { return _SkinNameValues[Skin.ToString().ToLower()]; }

        }



        internal string ClientObjectString
        {
            get
            {
                if (!DesignMode)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("{");
                    sb.AppendFormat("mode:\"{0}\"", "exact");
                    sb.Append(",");
                    sb.AppendFormat("elements:\"{0}\"", ClientID);
                    sb.Append(",");
                    sb.AppendFormat("plugins:\"{0}\"", Plugins);
                    sb.Append(",");

                    sb.AppendFormat("convert_urls : {0}", Convert.ToByte(ConvertUrls));
                    sb.Append(",");
                    // Skin Color 
                    sb.Append(ClientSkinString);
                    sb.Append(",");

                    sb.AppendFormat("theme:\"{0}\"", ThemeMode.ToString().ToLower());

                   
                    sb.Append(",");
                    sb.AppendFormat("inlinepopups_skin:\"{0}\"", Skin.ToString().ToLower());
                    

                    #region //Ren toolbar

                    for (int i = 0; i < ToolBarButtons.Length; i++)
                    {

                      
                        sb.Append(",");
                        sb.AppendFormat("theme_advanced_buttons{0}:\"{1}\"", i + 1, ToolBarButtons[i]);
                       

                    }

                    #endregion
                    
                    //

                    sb.Append(",");
                    sb.AppendFormat("theme_advanced_toolbar_location:\"{0}\"", ToolBarLocation.ToString().ToLower());

                    sb.Append(",");
                    sb.AppendFormat("theme_advanced_toolbar_align:\"{0}\"", ToolBarAlign.ToString().ToLower());


                    if (StatusBarLocation != EditorStatusBarLocation.None)
                    {
                        sb.Append(",");
                        sb.AppendFormat("theme_advanced_statusbar_location:\"{0}\"", StatusBarLocation.ToString().ToLower());

                    }

                    sb.Append(",");
                    sb.AppendFormat("theme_advanced_resizing:{0}", Resizing.ToString().ToLower());

                    sb.Append(",");
                    sb.Append("template_replace_values : {username : \"NASA8x\",staffid : \"118\"}");



                    if (IsAjaxEnable)
                    {

                        sb.Append(",");

                        sb.Append("setup : function(ed) {");


                        // On Content Change
                        sb.Append("ed.onChange.add(function(ed, o) {");
                        sb.Append("document.getElementById('" + ClientID + "').value=ed.getContent();"); // function body
                        sb.Append("});"); //End Function

                        // On onNodeChange
                        sb.Append("ed.onSetContent.add(function(ed, o) {");
                        sb.Append("document.getElementById('" + ClientID + "').value=ed.getContent();"); // function body
                        sb.Append("});"); //End Function

                        sb.Append("}"); // End Setup

                    }


                    sb.Append("}");


                    return sb.ToString();
                }
                return "";
            }
        }


        internal string ClientObjectCreationString
        {
            get
            {
                // return String.Format("window[\"{0}\"] = tinyMCE.init({1});", ClientID, ClientObjectString);
                return String.Format("tinyMCE.init({0});", ClientObjectString);
            }
        }


        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
       Browsable(false)]
        internal string InitScripts
        {
            get
            {
                return String.Format("<script type=\"text/javascript\">/*<![CDATA[*/{0}/*]]>*/</script>", ClientObjectCreationString);
                //return String.Format("<script type=\"text/javascript\">{0}</script>", ClientObjectCreationString);
            }
        }


        #endregion

        //#region Warning

        //private static void RenderRedistributableWarning(TextWriter output)
        //{
        //    output.Write(
        //        "<div style=\"background-color:#3F3F3F;border:1px;border-style:solid;border-bottom-color:black;border-right-color:black;border-left-color:lightslategray;border-top-color:lightslategray;color:cornsilk;padding:2px;font-family:verdana;font-size:11px;\">");

        //    output.Write(Utils.COPPY_RIGHT);
        //    output.Write("</div>");
        //}

        //#endregion
        

        protected override void OnInit(EventArgs e)
        {

            base.OnInit(e);
            TextMode = TextBoxMode.MultiLine;

          
            //Check Toolbar Button

            switch (ToolBarMode)
            {
               
                case EditorToolBarMode.Medium:
                    ToolBarButtons = _sMediumToolBarButtons;
                    break;

                case EditorToolBarMode.Simple:
                    Plugins =
                        "safari,pagebreak,style,layer,table,advhr,advlink,emotions,iespell,insertdatetime,preview,print,contextmenu,paste,directionality,noneditable,visualchars,nonbreaking,xhtmlxtras,fullscreen,inlinepopups";
                    ToolBarButtons=new string[]
                                       {
                                           "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,link,unlink,image,fullscreen",
                                           "",
                                           "",
                                           ""

                                       };
                    break;


            }


            if (!Page.ClientScript.IsClientScriptIncludeRegistered("Nasa8xScript_" + ControlName))
            {
                string _scriptUrl = ScriptPath + "tiny_mce.js";
                Page.ClientScript.RegisterClientScriptInclude(GetType(), "Nasa8xScript_" + ControlName, _scriptUrl);

            }

        }


        protected override void Render(HtmlTextWriter outWriter)
        {
            
            base.Render(outWriter);

            outWriter.Write(InitScripts);


        }
    }
}
